/*
 * @Author: bsj
 * @Date: 2024-03-29
 * @LastEditors: baoshijie
 * @LastEditTime: 2024-11-11
 * @Description: file content
 * @FilePath: \computing-equipment\src\store\modules\permission.js
 */
import { constantRoutes } from "@/router";
import { getmenu, getInfo, getAirlineCompany } from "@/api/login";
import ParentView from "@/components/ParentView";
import menu from './menu'


// 匹配views里面所有的.vue文件
let modules = import.meta.glob("./../../views/**/**.vue");
const  VITEAPPMENU=import.meta.env.VITE_APP_MENU

const permission = {
  state: {
    jurisdiction: [],
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
    indexRouter: "",
    btnPermissionData: [],
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes;
      state.routes = constantRoutes.concat(routes);
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes);
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      state.topbarRouters = routes;
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes;
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit, context }) {
      return new Promise((resolve) => {
          let res = menu;
          let sdata = JSON.parse(JSON.stringify(res));
          let rdata = JSON.parse(JSON.stringify(res));
          let defaultData = JSON.parse(JSON.stringify(res));
          filterAsyncRouter(sdata);
          filterAsyncRouter(rdata);
          filterAsyncRouter(defaultData);
          rdata.push({
            path: "/",
            redirect: '/login',
          });
          commit("SET_ROUTES", rdata);
          commit("SET_SIDEBAR_ROUTERS", constantRoutes.concat(sdata));
          commit("SET_DEFAULT_ROUTES", sdata);
          commit("SET_TOPBAR_ROUTES", defaultData);
          resolve(rdata);
      });
    },
  },
};

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(arr) {
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i];
    item.path = "/" + item.url;
    item.meta = {
      title: item.name,
    };

    if (item.type == 0) {
      item.redirect = item.children[0].url;
      item.component = ParentView;
      if (item.children) {
        filterAsyncRouter(item.children);
      }
    } else if (item.type == 1) {
      item.component = modules[`./../../views/${item.url}/index.vue`];
      item.children = null;
    }
  }
}

export default permission;
